package newcoder_exp.justPractise;
import java.util.*;
import org.junit.*;

public class NC125 {
    public class Solution {


        //累计和为k的最长子数组 【有负数和0】
        public int maxlenEqualK1 (int[] arr, int k) {
            return dfs(0, 0, 0, k, arr);
        }

        Map<String, Integer> map = new HashMap<>();
        public int dfs(int idx, int cur, int step,int target, int[] nums) {
            if (map.containsKey(idx + "_" + cur)) {
                System.out.println("击中缓存");
                return map.get(idx + "_" + cur);
            }
            if (idx == nums.length) {
                return cur == target ? step : -1;
            }
            int get = dfs(idx + 1, cur + nums[idx], step + 1, target, nums);
            int not = dfs(idx + 1, cur, step, target, nums);
            int res = Math.max(get, not);
            map.put(idx + "_" + cur, res);
            return res;
        }

        public int maxlenEqualK (int[] arr, int k) {
            int len = arr.length;
            int sub = 0, suf = 0;
            for (int i = 0; i < len; i++) {
                if (arr[i] > 0) suf += arr[i];
                else sub += arr[i];
            }
            int limit = suf - sub;
            int[][] f = new int[len + 1][limit + 1];
            for (int j = 0; j <= limit; j++) {
                f[len][j] = -1;
            }
            f[len][k - sub] = 0;
            for (int i = len - 1; i >= 0; i--) {
                for (int j = limit; j >= 0; j--) {
                    f[i][j] = f[i + 1][j] == -1 ? -1 : f[i + 1][j];
                    if (j + Math.abs(arr[i]) <= limit) {
                        if (f[i + 1][j + Math.abs(arr[i])] >= 0) 
                            f[i][j] = Math.max(f[i][j], f[i + 1][j + Math.abs(arr[i])] + 1);
                    }
                }
            }
            System.out.println(Arrays.deepToString(f));
            return f[0][-sub];
        }
    }

    @Test
    public void test() {
        Solution s = new Solution();
        int[] nums = new int[]{1,-2,1,1,1};
        int res = s.maxlenEqualK1(nums, 0);
        System.out.println(res);
    }
}
 